import re
from django.contrib.auth.backends import ModelBackend
from apps.users.models import User
from meiduo_mail import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadSignature, SignatureExpired

from django.http import JsonResponse


def get_user_by_username(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        user = None
    return user


class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_username(username)
        if user is not None and user.check_password(password):
            return user


    # def authenticate(self, request, username=None, password=None, **kwargs):
    #     if request is None:
    #         try:
    #             admin = User.objects.get(username=username, is_staff=True)
    #         except:
    #             admin = None
    #         if admin is not None and admin.check_password(password):
    #             return admin
    #
    #     else:
    #         try:
    #             user = User.objects.get(username=username)
    #         except:
    #             try:
    #                 user = User.objects.get(mobile=username)
    #             except:
    #                 return None
    #         if user.check_password(password):
    #             return user
    #         else:
    #             return None


def generic_verify_url(user_id):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60)
    token = s.dumps({'user_id': user_id})
    return 'http://www.meiduo.site:8000/email_active/?token=%s' % token.decode()


def check_verify_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except BadSignature:
        return None
    user_id = result.get('user_id')
    return user_id
